package config

import (
	"fmt"
	"log"
	"os"
	"sync"
	"time"

	"gopkg.in/yaml.v3"
)

var (
	globalConfig *Config
	configMutex  sync.RWMutex
)

// Config 主配置结构
type Config struct {
	Server       ServerConfig       `yaml:"server"`
	Database     DatabaseConfig     `yaml:"database"`
	TLS          TLSConfig          `yaml:"tls"`
	JWT          JWTConfig          `yaml:"jwt"`
	OAuth2       OAuth2Config       `yaml:"oauth2"`
	RateLimit    RateLimitConfig    `yaml:"rate_limit"`
	Routes       []RouteConfig      `yaml:"routes"`
	CORS         CORSConfig         `yaml:"cors"`
	Security     SecurityConfig     `yaml:"security"`
	Logger       LoggerConfig       `yaml:"logger"`
	Monitor      MonitorConfig      `yaml:"monitor"`
	ConfigReload ConfigReloadConfig `yaml:"config_reload"`
}

// ServerConfig 服务器配置
type ServerConfig struct {
	Host          string        `yaml:"host"`
	Port          int           `yaml:"port"`
	Mode          string        `yaml:"mode"`
	ReadTimeout   time.Duration `yaml:"read_timeout"`
	WriteTimeout  time.Duration `yaml:"write_timeout"`
	MaxHeaderBytes int          `yaml:"max_header_bytes"`
}

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	Enabled         bool          `yaml:"enabled"`
	Type            string        `yaml:"type"` // mysql, postgres, sqlite
	Host            string        `yaml:"host"`
	Port            int           `yaml:"port"`
	User            string        `yaml:"user"`
	Password        string        `yaml:"password"`
	Database        string        `yaml:"database"`
	MaxOpenConns    int           `yaml:"max_open_conns"`
	MaxIdleConns    int           `yaml:"max_idle_conns"`
	ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime"`
}

// TLSConfig HTTPS 配置
type TLSConfig struct {
	Enabled  bool   `yaml:"enabled"`
	CertFile string `yaml:"cert_file"`
	KeyFile  string `yaml:"key_file"`
}

// JWTConfig JWT 配置
type JWTConfig struct {
	Secret            string `yaml:"secret"`
	Issuer            string `yaml:"issuer"`
	Expiration        int    `yaml:"expiration"`
	RefreshExpiration int    `yaml:"refresh_expiration"`
}

// OAuth2Config OAuth2 配置
type OAuth2Config struct {
	Enabled   bool                      `yaml:"enabled"`
	Providers map[string]OAuth2Provider `yaml:"providers"`
}

// OAuth2Provider OAuth2 提供商配置
type OAuth2Provider struct {
	ClientID     string `yaml:"client_id"`
	ClientSecret string `yaml:"client_secret"`
	RedirectURL  string `yaml:"redirect_url"`
	AuthURL      string `yaml:"auth_url"`
	TokenURL     string `yaml:"token_url"`
}

// RateLimitConfig 限流配置
type RateLimitConfig struct {
	Enabled bool              `yaml:"enabled"`
	Strategy string           `yaml:"strategy"`
	Global   RateLimitRule    `yaml:"global"`
	PerIP    RateLimitRule    `yaml:"per_ip"`
	PerUser  RateLimitRule    `yaml:"per_user"`
}

// RateLimitRule 限流规则
type RateLimitRule struct {
	Enabled bool `yaml:"enabled"`
	QPS     int  `yaml:"qps"`
	Burst   int  `yaml:"burst"`
}

// RouteConfig 路由配置
type RouteConfig struct {
	Name        string        `yaml:"name"`
	Path        string        `yaml:"path"`
	Target      string        `yaml:"target"`
	Methods     []string      `yaml:"methods"`
	AuthRequired bool         `yaml:"auth_required"`
	RateLimit   RateLimitRule `yaml:"rate_limit"`
}

// CORSConfig CORS 配置
type CORSConfig struct {
	Enabled        bool     `yaml:"enabled"`
	AllowOrigins   []string `yaml:"allow_origins"`
	AllowMethods   []string `yaml:"allow_methods"`
	AllowHeaders   []string `yaml:"allow_headers"`
	AllowCredentials bool   `yaml:"allow_credentials"`
	MaxAge         int      `yaml:"max_age"`
}

// SecurityConfig 安全配置
type SecurityConfig struct {
	Headers     map[string]string `yaml:"headers"`
	IPWhitelist IPWhitelistConfig  `yaml:"ip_whitelist"`
}

// IPWhitelistConfig IP 白名单配置
type IPWhitelistConfig struct {
	Enabled bool     `yaml:"enabled"`
	IPs     []string `yaml:"ips"`
}

// LoggerConfig 日志配置
type LoggerConfig struct {
	Level  string      `yaml:"level"`
	Format string      `yaml:"format"`
	Output string      `yaml:"output"`
	File   LoggerFileConfig `yaml:"file"`
}

// LoggerFileConfig 日志文件配置
type LoggerFileConfig struct {
	Path      string `yaml:"path"`
	MaxSize   int    `yaml:"max_size"`
	MaxBackups int   `yaml:"max_backups"`
	MaxAge    int    `yaml:"max_age"`
	Compress  bool   `yaml:"compress"`
}

// MonitorConfig 监控配置
type MonitorConfig struct {
	Prometheus PrometheusConfig `yaml:"prometheus"`
}

// PrometheusConfig Prometheus 配置
type PrometheusConfig struct {
	Enabled bool   `yaml:"enabled"`
	Path    string `yaml:"path"`
	Port    int    `yaml:"port"`
}

// ConfigReloadConfig 配置热更新配置
type ConfigReloadConfig struct {
	Enabled      bool          `yaml:"enabled"`
	WatchInterval time.Duration `yaml:"watch_interval"`
	ConfigFile   string        `yaml:"config_file"`
}

// Load 加载配置文件
func Load(path string) (*Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("读取配置文件失败: %w", err)
	}

	var cfg Config
	if err := yaml.Unmarshal(data, &cfg); err != nil {
		return nil, fmt.Errorf("解析配置文件失败: %w", err)
	}

	configMutex.Lock()
	globalConfig = &cfg
	configMutex.Unlock()

	return &cfg, nil
}

// Get 获取全局配置
func Get() *Config {
	configMutex.RLock()
	defer configMutex.RUnlock()
	return globalConfig
}

// Reload 重新加载配置
func Reload(path string) error {
	newCfg, err := Load(path)
	if err != nil {
		return err
	}

	configMutex.Lock()
	globalConfig = newCfg
	configMutex.Unlock()

	log.Println("配置热更新成功")
	return nil
}

// WatchConfig 监听配置文件变化
func WatchConfig(configFile string, interval time.Duration) {
	ticker := time.NewTicker(interval)
	defer ticker.Stop()

	var lastModTime time.Time
	info, err := os.Stat(configFile)
	if err == nil {
		lastModTime = info.ModTime()
	}

	for range ticker.C {
		info, err := os.Stat(configFile)
		if err != nil {
			continue
		}

		if info.ModTime().After(lastModTime) {
			lastModTime = info.ModTime()
		if err := Reload(configFile); err != nil {
			log.Printf("配置热更新失败: %v", err)
		}
		}
	}
}

// MigrateToDB 迁移配置到数据库
func MigrateToDB(cfg *Config) error {
	// 导入 migration 包避免循环依赖，这里先简化处理
	// 实际应该在 migration 包中实现
	return nil
}

